package net.dfrz.service;

import java.util.List;


import net.dfrz.dao.GoodsDao;
import net.dfrz.dao.GoodsDaoJDBCImpl;
import net.dfrz.domain.Goods;
import net.dfrz.exception.ClientException;
import net.dfrz.utils.DBUtils;
import net.dfrz.utils.GoodsSearchHelper;
import net.dfrz.utils.Page;
import net.dfrz.utils.TransactionManager;

public class GoodsServiceImpl implements GoodsService {


public void add(Goods goods) {
		
		GoodsDao dao=new GoodsDaoJDBCImpl();
		TransactionManager manager=DBUtils.getInstance().getTransactionManager();
		
		manager.beginTransaction();
		try{
			dao.add(goods);
			manager.commitAndClose();
		}catch(ClientException e){
			manager.rollbackAndClose();
			throw new ClientException(e.getMessage());
		}
		
	}

	public List<Goods> loadGoods() {
		
		GoodsDao dao=new GoodsDaoJDBCImpl();
		TransactionManager manager=DBUtils.getInstance().getTransactionManager();
		List<Goods> goodsList=null; 
		
		manager.beginTransaction();
		try{
			goodsList=dao.loadGoods();
			manager.commitAndClose();
		}catch(ClientException e){
			manager.rollbackAndClose();
			throw new ClientException(e.getMessage());
		}
		
		return goodsList;
		
	}

	public byte[] getPic(Integer goodsNo) {
		
		GoodsDao dao=new GoodsDaoJDBCImpl();
		TransactionManager manager=DBUtils.getInstance().getTransactionManager();
		byte[] goodsPic=null;
		
		manager.beginTransaction();
		try{
			goodsPic=dao.getPic(goodsNo);
			manager.commitAndClose();
		}catch(ClientException e){
			manager.rollbackAndClose();
			throw new ClientException(e.getMessage());
		}
		
		return goodsPic;
		
	}

	public void del(Integer goodsno) {
		GoodsDao dao=new GoodsDaoJDBCImpl();
		dao.del(goodsno);
		
	}

	public void deleteAllByCategoryNo(Integer categoryNo) {
		// TODO Auto-generated method stub
		
	}

	public Goods getGoodsById(Integer goodsno) {
		GoodsDao dao=new GoodsDaoJDBCImpl();
		return dao.getGoodsById(goodsno);
	}

	public void updateGoods(Goods goods) {
		GoodsDao dao=new GoodsDaoJDBCImpl();
		dao.updateGoods(goods);
		
	}


	public long countByHelper(GoodsSearchHelper gSearchHelper) {
		GoodsDao dao=new GoodsDaoJDBCImpl();
		return dao.countGoodByHelper(gSearchHelper);
	}


	public Page loadScopeGoods(Page page, GoodsSearchHelper gSearchHelper) {
		TransactionManager manager = DBUtils.getInstance().getTransactionManager();
		GoodsDao dao=new GoodsDaoJDBCImpl();

		manager.beginTransaction();

		try {
			page.setPageContent(dao.loadScopeGoods(gSearchHelper,
					page.getStartIndex(), page.getEndIndex()));
		} catch (ClientException e) {
			manager.rollbackAndClose();
			throw e;
		}

		manager.commitAndClose();

		return page;

	}

}
